package com.action.library;

import java.util.ArrayList;


import com.bean.library.AppraisedOption;
import com.bean.library.AppraisedPaper;
import com.bean.library.AppraisedSubject;
import com.bean.library.Option;
import com.bean.library.Paper;
import com.bean.library.Subject;
import com.bean.library.UserOption;
import com.bean.library.UserPaper;
import com.dao.DaoManager;
import com.dao.library.PaperDao;
import com.dao.library.StudentDao;

public class AppraisePaperAction {
	public AppraisedPaper getAppraisedPaper(UserPaper userPaper){
		AppraisedPaper appraisedPaper = new AppraisedPaper(userPaper);
		ArrayList<Subject> appraisedSubjectList = appraisedPaper.getSubjectList();
		DaoManager dm = DaoManager.getInstance();
		PaperDao paperDao = dm.getDao(PaperDao.class);
		
		int countRight = 0;
		int subCount = appraisedSubjectList.size();
		
		try
		{
			dm.begin();
			for(int i =- 0;i<subCount;i++){
				AppraisedSubject appraisedSubject = (AppraisedSubject)appraisedSubjectList.get(i);
				ArrayList<Option> appraisedOptionList = appraisedSubject.getOptList();
				int optCount = appraisedOptionList.size();
				boolean subjectIsRight = true;
				for(int j = 0;j<optCount;j++){
					AppraisedOption appraisedOption = (AppraisedOption)appraisedOptionList.get(j);
					int optId = appraisedOption.getOptId();
					boolean stdAnswer = paperDao.isOptinRight(optId);
					appraisedOption.setRight(stdAnswer);
					boolean userAnswer = appraisedOption.isChecked();
					if(stdAnswer!=userAnswer){
						subjectIsRight = false;//一个选项错了本道题就错了。
					}
				}
				if(subjectIsRight){
					countRight ++;//回答正确
					appraisedSubject.setRight(true);
				}
				else {
					appraisedSubject.setRight(false);
				}
			}
			dm.commit();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally 
		{
			dm.end();
		}
		float paperScore = appraisedPaper.getPaperScore();
		float userScore = paperScore/subCount*countRight; 
		appraisedPaper.setScore(userScore);
		return appraisedPaper;
	}
	public boolean saveStudentScore(String studentId, int paperId, float score){
		DaoManager dm = DaoManager.getInstance();
		StudentDao studentDao = dm.getDao(StudentDao.class);
		boolean result = false;
		try
		{
			dm.begin();
			result = studentDao.saveScore(studentId, paperId, score);
			dm.commit();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally 
		{
			dm.end();
		}
		return result;
	}
}
